import md5 from 'md5'
import {MineMessage} from '@/libs'

/**
 * 用户
 */
export default {
    //独立作用域
    namespaced: true,
    state: () => {
        return {
            //登录中的token
            token: 'cd16016a9f8e990cc6e9a8bd09c1c513',
            userInfo: {}
        }
    },
    mutations: {
        //保存token
        setToken(state, newToken) {
            state.token = newToken
        },
        setUserInfo(state, newUserInfo) {
            state.userInfo = newUserInfo
        }
    },
    actions: {
        /**
         * 登录
         */
        login(context, payload) {
            //加密密码
            const {password} = payload
            //调用登录方法
            const params = {
                ...payload,
                password: password ? md5(password) : ''
            }
            //保存token
            context.commit('setToken', 'cd16016a9f8e990cc6e9a8bd09c1c513')
            //获取用户信息
            context.dispatch('profile')
        },
        /**
         * 获取用户信息
         */
        profile(context) {
            //TODO:请求接口
            const data = {
                vipLevel: '5',
                nickName: '测试用户',
                title:"title",
                company:"company",
                homepage:"homepage",
                introduction:"introduction",
                avatar:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic%2Ffe%2F11%2F97%2Ffe119792285b42e687ebf4367f77c8de.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1664615298&t=f5f11c75c4fe9a5c8b2ba87def3f1ef0'
            }
            context.commit('setUserInfo', data)
            MineMessage('success', `欢迎您${data.vipLevel ? '尊贵的vip-' + data.vipLevel + '用户:' + data.nickName : data.nickName}`, 6000)
        },
        /**
         * TODO:退出登录
         */
        logout(context) {
            // 清空token
            context.commit('setToken', '')
            //清空用户信息
            context.commit('setUserInfo', {})
            //刷新页面
            location.reload()
        },
        /**
         * 注册
         * @returns {Promise<void>}
         */
        async register(context, payload) {
            const {password} = payload
            //TODO:注册接口
            const params = {
                ...payload,
                password: password ? md5(password) : ''
            }
        }
    }
}
